package com.cc.advice;


import com.cc.anotation.IgnoreResponseAdvice;
import com.cc.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import static com.cc.vo.CommonResponse.SUCCESS;

/**
 * @author CHENCHEN
 * @company 北京学佳澳教育科技
 * @create 2023-03-02 15:23
 */
@RestControllerAdvice("com.cc.flyingfish")
public class CommonResponseDataAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //如果类上面包含@IgnoreResponseAdvice注解，不返回处理参数
        if(methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)){
            return false;
        }
        //如果方法上面包含@IgnoreResponseAdvice注解，不返回处理参数
        if(methodParameter.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)){
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        CommonResponse commmonResponse = SUCCESS;
        if(o == null){
            return commmonResponse;
        }else if(o instanceof CommonResponse){
            return o;
        }else{
            commmonResponse.setData(o);
        }
        return commmonResponse;
    }
}
